//
//  File.swift
//  
//
//  Created by WeCloudIOS on 2022/4/13.
//

import Foundation
import UIKit

extension Double {
    func roundTo(places: Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}


class VideoListView : UIView{
    
    lazy var scrollView: UIScrollView = {
        
        let scrollView = UIScrollView()
        scrollView.backgroundColor = UIColor.gray
        scrollView.frame = CGRect(x: 0, y: 0, width: Windos.w, height: Windos.h-100)
        return scrollView
    }()
    
    var listen: RoomListener?
    var room:WCObservableRoom?
    var trackViewArray = [WCVideoView]()
    
    init() {
        super.init(frame: CGRect.zero)
        addSubview(self.scrollView)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func show(){
        setUI()
    }
    
    func setUI(){
        let h: Double = Double(room!.allParticipants.count)/2.0
        let sh: CGFloat = h.rounded()*((Windos.w-30)/2+50) + h.rounded()*10
        scrollView.contentSize = CGSize(width: Windos.w, height: sh)
        addVideoView()
    }
    
    func addVideoView(){
        
        let count = room!.allParticipants.count - trackViewArray.count
        
        if count > 0{//要增加
            var number = 0
            while number < count{
                let video = WCVideoView()
                scrollView.addSubview(video)
                trackViewArray.append(video)
                number+=1
            }
            
        }else if count < 0{ //要删除
            var number = 0
            while number < -count{
                let video = trackViewArray[number]
                video.removeFromSuperview()
                trackViewArray.remove(at: number)
                number += 1
            }
        }
        
        
        var index = 0
        for (_,value) in room!.allParticipants.elements{
            
            let video = trackViewArray[index]
            let y = Int((Windos.w-30)/2+50)*(index/2) + (index/2)*10+10
            
            var x = 10
            if ((index%2) != 0){
                x = Int((Windos.w-30)/2)+20
            }
            
            video.frame = CGRect(x:CGFloat(x), y: CGFloat(y), width: (Windos.w-30)/2, height: (Windos.w-30)/2+50)
            if value.firstVideoAvailable{
                video.coverImgage.isHidden = true
                video.userInfo = value.identity
                video.videoData = value.firstCameraVideoTrack!
            }else{
                video.userInfo = value.identity
                video.coverImgage.isHidden = false
            }
            
            if value.firstAudioAvailable{
                video.voiceImgage.isHidden = true
            }else{
                video.voiceImgage.isHidden = false
            }
            
            let tap = UITapGestureRecognizer.init(target: self, action: #selector(tapAction))
            video.addGestureRecognizer(tap)
            index += 1
        }
    }
    
    @objc func tapAction(){
        listen?.upDateState()
        removeFromSuperview()
        for view in subviews{
            view.removeFromSuperview()
        }
    }
}

class VideoDefaultView : UIView{
    
    //对方视图
    lazy var remoteVideoView: VideoView = {
        let videoView = VideoView()
        videoView.backgroundColor = UIColor.gray
        return videoView
    }()
    
    //我方视图
    lazy var localVideoView: WCVideoView = {
        let videoView = WCVideoView()
        return videoView
    }()
    
    //用户封面吐
    let coverImgage:UIImageView = {
        let imageView = UIImageView()
        imageView.image = Tool.SCImage(named: "firm_evaluation_avatar")
        imageView.backgroundColor = UIColor.gray
        return imageView
    }()
    
    
    var bigCoverUrl:String?
    
    init() {
        super.init(frame: CGRect.zero)
        setUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUI(){
        addSubview(remoteVideoView)
        addSubview(coverImgage)
        addSubview(localVideoView)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        remoteVideoView.frame = CGRect(x: 0, y: 0, width: Windos.w, height: Windos.h)
        localVideoView.frame = CGRect(x:Windos.w-130, y: 50, width: 120, height: 200)
        coverImgage.frame = remoteVideoView.frame
    }
    
    func setVideo(track1: VideoTrack?,track2: Any?,outTrackName: String?) {
        localVideoView.voiceImgage.isHidden = true
        if track1 == nil{//自己并未订阅
            let data: NSDictionary? = UserDefaults.standard.value(forKey: "myUserInfo") as? NSDictionary
            localVideoView.nameLabel.text = data?.object(forKey: "nickname") as? String
            localVideoView.userInfo = data?.object(forKey: "userId") as? String ?? ""
            localVideoView.voiceImgage.isHidden = true
            localVideoView.coverImgage.isHidden = false
            
        }else{//自己已订阅
            localVideoView.coverImgage.isHidden = true
            let data: NSDictionary? = UserDefaults.standard.value(forKey: "myUserInfo") as? NSDictionary
            localVideoView.nameLabel.text = data?.object(forKey: "nickname") as? String
            localVideoView.userInfo = data?.object(forKey: "userId") as? String ?? ""
            localVideoView.videoData = track1!
        }
        
        if track2 == nil{//无人再房间的情况
            coverImgage.isHidden = false
            coverImgage.image = Tool.SCImage(named: "firm_evaluation_avatar")
        }else{
            
          let data = track2 as? ObservableParticipant
            if data != nil && data!.firstVideoAvailable{//有人在房间 有人打开视频
                coverImgage.isHidden = true
                remoteVideoView.track = data!.firstCameraVideoTrack
                setUserInfo(userId: data!.identity)
            }else{//有人在房间但无人打开视频
                coverImgage.isHidden = false
                setUserInfo(userId: data!.identity)
            }
        }
        
        //都没人打开摄像头
        if track1 == nil && track2 == nil{
            coverImgage.isHidden = false
            coverImgage.image = Tool.SCImage(named: "firm_evaluation_avatar")
        }
    }
    
    func setNewMaxVideo(track: VideoTrack){
        remoteVideoView.track = track
    }
    
    func setUserInfo(userId: String){
        
        if bigCoverUrl != nil{
            self.coverImgage.dowloadFromServer(link:bigCoverUrl!)
            return
        }
        
        let params:NSMutableDictionary = NSMutableDictionary()
        params["userId"] = userId
        
        NetWork(url: "/api/user/getUserByUserId", params: params) { obj in
            let data: NSDictionary = obj as! NSDictionary
            
            DispatchQueue.main.async {
                if data.object(forKey: "headPortrait") != nil{
                    
                    let link: String? = data.object(forKey: "headPortrait") as? String
                    if link != nil{
                        self.bigCoverUrl = link
                        self.coverImgage.dowloadFromServer(link: link!)
                    }else{
                        self.coverImgage.image = Tool.SCImage(named: "firm_evaluation_avatar")
                    }
                    
                }else{
                    print("用户头像为空")
                }
            }
        }
        
    }
    
}

